package com.tian.excel.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.Verification;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Tian
 * @version: 1.0
 * @since: 1.0
 * @date: 2024/7/30/9:59
 */
public class JWTUtil {
    private final static String  KEY="tian";
    public static String createToken(Map<String,Object> map){
        HashMap<String, Object> head = new HashMap<>();
        head.put("alg","HS256");
        head.put("type","JWT");
        //发布日期
        Date date=new Date();
        Calendar instance= Calendar.getInstance();
        instance.set(Calendar.SECOND,7200);
        Date time=instance.getTime();
        String token = JWT.create()
                .withHeader(head)
                .withIssuedAt(date)
                .withExpiresAt(time)
                .withClaim("userInfo", map)
                .sign(Algorithm.HMAC256(KEY));

        return token;
    }

    //检验token
    public  static boolean  verify(String token){
        Verification require=JWT.require(Algorithm.HMAC256(KEY));
        try{
            require.build().verify(token);
            return true;
        }catch (Exception e){
            System.out.println("token不存在");
            return false;
        }
    }


    //根据token获取自定义的信息
    public static Map<String,Object> getInfo(String token,String key){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(KEY)).build();
        Claim claim = build.verify(token).getClaim(key);
        return claim.asMap();
    }

}
